package security;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import dao.interf.IAuthorityDAO;
import dao.interf.IUserDAO;
import dao.pojo.Authority;
import dao.pojo.User;

public class MyUserDetailsService implements UserDetailsService {

	protected MessageSourceAccessor messages;
	private String rolePrefix;
	private IUserDAO userDao;
	private IAuthorityDAO authDao;
	
	public MyUserDetailsService() {
		messages = SpringSecurityMessageSource.getAccessor();
	}
	
	public void setAuthDao(IAuthorityDAO authDao) {
		this.authDao = authDao;
	}

	public void setUserDao(IUserDAO userDao) {
		this.userDao = userDao;
	}
	
	public String getRolePrefix() {
		return rolePrefix;
	}

	public void setRolePrefix(String rolePrefix) {
		this.rolePrefix = rolePrefix;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = null;
		
		try {
			List<User> users = userDao.findByProperties(new String[]{"userName"},
					new Object[]{username});
			if(!users.isEmpty()) {
				user = users.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(null == user) {
			 throw new UsernameNotFoundException(messages.getMessage("JdbcDaoImpl.notFound", 
					 new Object[]{username}, "用户 {0} 不存在"), username); 
		}
		MyUserDetails userDetails = new MyUserDetails();
		userDetails.setUsername(user.getUserName());
		userDetails.setPassword(user.getPassword());
		userDetails.setAccountNonLocked(true);
		userDetails.setAccountNonExpired(true);
		userDetails.setCredentialsNonExpired(true);
		
		if(1 == user.getEnabled()) {
			userDetails.setEnabled(true);
			List<Authority> auths = authDao.findAuthorityByUser(user);
			System.out.println("myuserDetailsService: " + username
					+ " " + auths.get(0).getAuthorityName());
			Set<GrantedAuthorityImpl> dbAuths= new HashSet(0);
			for(Iterator<Authority> ite = auths.iterator();ite.hasNext();){
	        	Authority a = ite.next();
	        	GrantedAuthorityImpl authority = new GrantedAuthorityImpl(a.getAuthorityName());
	        	dbAuths.add(authority);
	        }
	        userDetails.setAuthorities(dbAuths);
		} else {
			userDetails.setEnabled(false);
		}
		
		return userDetails;
	}

}
